package com.itheima.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.itheima.dubbo.utils.IdWorker;
import com.itheima.model.mongo.Peachblossom;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;

import java.util.List;

@DubboService
public class PeachblossomApiImpl implements PeachblossomApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdWorker idWorker;
    @Override
    public String save(Peachblossom peachblossom) {
        peachblossom.setCreated(System.currentTimeMillis());
        peachblossom.setLid(idWorker.getNextId("peachblossom"));
        mongoTemplate.save(peachblossom);
        return peachblossom.getId().toString();
    }

    @Override
    public Peachblossom queryExtendLids(List<Long> lids) {
        Criteria criteria = new Criteria();
        if(!CollUtil.isEmpty(lids)){
            criteria= Criteria.where("lid").nin(lids);
        }
        TypedAggregation aggregation =  TypedAggregation.newAggregation(Peachblossom.class, Aggregation.match(criteria),Aggregation.limit(1));

        AggregationResults<Peachblossom> aggregate = mongoTemplate.aggregate(aggregation, Peachblossom.class);
        return aggregate.getMappedResults().size()==0?null:aggregate.getMappedResults().get(0);

    }
}
